import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import FormInput from '../components/FormInput';
import SubmitButton from '../components/SubmitButton';
import { register } from '../services/api';

const Register: React.FC = () => {
    const navigate = useNavigate();
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [error, setError] = useState('');

    const handleRegister = async () => {
        if (password !== confirmPassword) {
            setError('两次密码不一致');
            return;
        }
        try {
            await register(username, email, password);
            navigate('/login');
        } catch (err: any) {
            setError(err.response?.data?.error || '注册失败');
            console.error(err.response.data.error);
        }
    };

    return (
        <div className="auth-container">
            <h2>IAM统一注册平台</h2>
            <p>请填写以下信息创建账号</p>
            {error && <p className="error">{error}</p>}
            <FormInput label="用户名" placeholder="请输入用户名" value={username} onChange={(e) => setUsername(e.target.value)} />
            <FormInput label="邮箱" placeholder="请输入邮箱地址" value={email} onChange={(e) => setEmail(e.target.value)} />
            <FormInput label="密码" placeholder="请设置密码" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
            <FormInput label="确认密码" placeholder="请再次输入密码" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} />
            <SubmitButton text="注册" onClick={handleRegister} />
            <p>已有账号？<a href="#" onClick={() => navigate('/login')}>返回登录</a></p>
        </div>
    );
};

export default Register;